import WebApp from '@twa-dev/sdk';

export const checkEmialValid = (email?: string) => {
    if (!email) {
        return false
    }
    const reg = /^(?:[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:(?:\.\w{2,}){1,2})?)$/;
    return reg.test(email)
}

export const checkPasswordValid = (password?: string) => {
    if (!password) {
        return false
    }
    if (password.length < 6 || password.length > 15) {
        return false
    }
    return true
}


export enum OSType {
    Android = 1,
    iOS = 2,
    PC = 3
}

enum PlatformType {
    iOS = 'ios',
    android = 'android',
    h5 = 'h5',
    unknown = 'unknown'
}

export type UpdateInfo = {
    content: string;
    url: string;
    type: PlatformType
}


let g_OSType = 0;
let g_platform = '';

export const fetchOS = (): OSType => {
    if (!g_OSType) {
        const u = navigator.userAgent;
        const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;   //判断是否是 android终端
        const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);     //判断是否是 iOS终端
        if (isAndroid) {
            g_OSType = OSType.Android
        } else if (isIOS) {
            g_OSType = OSType.iOS
        } else {
            g_OSType = OSType.PC
        }
    }

    return g_OSType
}

const getPlatformFromUserAgent = () => {
    const userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.includes('windows')) {
        return 'Windows';
    } else if (userAgent.includes('macintosh') || userAgent.includes('mac os')) {
        return 'Mac';
    } else if (userAgent.includes('iphone') || userAgent.includes('ipad') || userAgent.includes('ipod')) {
        return 'iOS';
    } else if (userAgent.includes('android')) {
        return 'Android';
    } else {
        return 'Unknown';
    }
}

let g_isFromMobile = false;
export const setIsFromMobile = (value: boolean) => {
    g_isFromMobile = value;
}

export const isFromMobile = (): boolean => {
    return g_isFromMobile;
}

export const platform = () => {
    if (g_platform) {
        return g_platform
    }

    if (WebApp.platform) {
        g_platform = WebApp.platform;
        return g_platform
    }

    g_platform = getPlatformFromUserAgent().toLowerCase();
    return g_platform
}

export const isIOS = () => {
    return platform() === PlatformType.iOS
}

export const isAndroid = () => {
    return platform() === PlatformType.android
}

export const isMobile = () => {
    const p = platform().toLowerCase();
    return p === PlatformType.iOS || p === PlatformType.android
}

export const isSupport = () => {
    if (isDev()) {
        return true
    }

    return isMobile()

}

export const isDev = () => {
    return process.env.REACT_APP_ENV === 'development'
}

export const isTest = () => {
    return process.env.REACT_APP_ENV === 'test'
}

export const isProduction = () => {
    return process.env.REACT_APP_ENV === 'production'
}
